package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.project.entity.Order;
import com.project.entity.PreOrder;
import com.project.entity.Product;
import com.project.mapper.PreOrderMapper;
import com.project.mapper.ProductMapper;
import com.project.service.PreOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lovo
 * @since 2023-07-21
 */
@Service
public class PreOrderServiceImp extends ServiceImpl<PreOrderMapper, PreOrder> implements PreOrderService {

    @Autowired
    private ProductMapper productMapper;
    @Override
    public List<Product> findById(Integer factoryId) {
        return this.baseMapper.findById(factoryId);
    }

    @Override
    public void addProduct(Product product,Integer inNum,Integer userId,Integer factoryId) {
        QueryWrapper qw = new QueryWrapper<>();
        qw.eq("fk_factoryId",factoryId);
        qw.eq("fk_productId",product.getProductId());
        PreOrder preOrder =  this.baseMapper.selectOne(qw);
      //判断入库表中是否有该商品
   if (preOrder != null){
       //商品存在,修改购买数量（采购数量+添加的数量）
       preOrder.setInNum(product.getStoreNum()+inNum);
       this.baseMapper.updateById(preOrder);
   }else {
       //商品不存在
       product.setFactoryId(factoryId);
       product.setStoreNum(inNum);
       //添加商品
       //根据商品Id和供应商ID判断商品表中是否有改商品
      Product pro = productMapper.findById(product.getProductId(),factoryId);
       if (pro != null){
           //商品表存在商品
           PreOrder po = new PreOrder();
           po.setInNum(pro.getStoreNum()+inNum);
           po.setUserId(userId);
           po.setFactoryId(pro.getFactoryId());
           po.setProductId(pro.getProductId());

       }else {
           //商品表不存在
           productMapper.insert(product);
           PreOrder p = new PreOrder();
           p.setInNum(inNum);
           p.setProductId(product.getProductId());
           p.setFactoryId(factoryId);
           p.setUserId(userId);
           this.baseMapper.insert(p);
       }


   }
    }

    @Override
    public void updateByInNum(Integer factoryId, Integer productId, Integer inNum) {
        QueryWrapper qw = new QueryWrapper<>();
        qw.eq("fk_factoryId",factoryId);
        qw.eq("fk_productId",productId);
        PreOrder preOrder =  this.baseMapper.selectOne(qw);

        preOrder.setInNum(inNum);
        this.baseMapper.updateById(preOrder);
    }

    @Override
    public void delByProduct(Integer factoryId, Integer productId) {
        QueryWrapper qw = new QueryWrapper<>();
        qw.eq("fk_factoryId",factoryId);
        qw.eq("fk_productId",productId);

        PreOrder preOrder =  this.baseMapper.selectOne(qw);
        this.baseMapper.deleteById(preOrder.getPreOrderId());
    }

}
